package servlet;

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

import common.Property;
import common.SkillManInstance;
import common.SkillManSchema;

public class insertInstance extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static String cwd=Property.skillMgmHome;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


		request.getSession(true); 
		
		SkillManSchema r=new SkillManSchema();
		r.setCWD(Property.skillMgmHome);
		r.load();

		String login=request.getParameter("login");
		String nome=request.getParameter("nome");
		
		System.out.println("Login: "+login);
		System.out.println("Name: "+nome);
		
		SkillManInstance i = new SkillManInstance(r, login+".owl");
		i.setCWD(Property.instances);
		i.loadDefault(Property.skillMgmHome+"dafault_instance.owl");
		// set Person name
		i.setPropertyValue(SkillManInstance.foafNS+"Person", SkillManInstance.foafNS+"name" ,nome);
		
		Enumeration<String> e=request.getParameterNames();
		int numParent=0;
		while (e.hasMoreElements())
		{
			String c=e.nextElement();
			if(c.contains("parent"))
			{
				numParent++;
			}
		}
		//System.out.println(numParent);
		for(int j=0;j<numParent;j++){
			String skill=request.getParameter("parent"+j);
			String leve=request.getParameter("level"+j);
			int livello=Integer.parseInt(leve);
			i.addSkill(skill, livello);
			System.out.println("Inserted skill: "+skill);
			System.out.println("With level: "+livello);
		}
		
		
		try {
			i.store();
			r.store();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			System.out.println("Errore nel salvataggio");
			e1.printStackTrace();
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
		dispatcher.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
